// pages/mine/advice/advice.js
const recorderManager = wx.getRecorderManager();
var app = getApp();
var md5 = require('../../../libs/md5.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    is_clock: false,
    startPoint: '',
    luyinpop:false,
    startPoint: '',
    yiluyin: false,
    yuyinsrc:'',
    luyintime:'',
    playing:false,
    tijiaozhong:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.luyin = this.selectComponent("#luyin");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /******语音描述-录音******/
  luyintap: function (e) {
      this.luyin.luyin();
  },

  // 开始录音
  handleRecordStart: function (e) {
    console.log(e)
    this.setData({
      is_clock: true,//长按时应设置为true，为可发送状态
      startPoint: e.detail.e.touches[0],//记录触摸点的坐标信息
      luyinzhong: true,//录音跳动
    })
    //设置录音参数
    const options = {
      duration: 300000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(options);
  },
  // 松开发送
  handleRecordStop: function (e) {
    recorderManager.stop()//结束录音
    //此时先判断是否需要发送录音
    
      var that = this
      //对停止录音进行监控
      recorderManager.onStop((res) => {
        console.log(res)
        if (that.data.is_clock == true) {
            //对录音时长进行判断，少于2s的不进行发送，并做出提示
            if (res.duration < 2000) {
              wx.showToast({
                title: '录音时间太短，请长按录音',
                icon: 'none',
                duration: 1000
              })
            } else {
              //进行语音发送
              const {
                tempFilePath
              } = res;
              // wx.showLoading({
              //   title: '语音检索中',
              // })
              console.log(res.tempFilePath)
              this.setData({
                'yuyinsrc': res.tempFilePath,
                'luyintime': Math.floor(res.duration / 1000),
                'yiluyin': true
              });
            }
        }
        
      })
    
  },
  // 滑动取消发送
  handleTouchMove: function (e) {
    //计算距离，当滑动的垂直距离大于25时，则取消发送语音
    if (Math.abs(e.detail.touches[0].clientY - this.data.startPoint.clientY) > 30) {
      this.setData({
        is_clock: false,//设置为不发送语音
        luyinpop: false,
        luyinzhong: false,
        yiluyin: false,
        yuyinsrc: ''
      })
    }
  },
  // 播放录音
  // 播放录音
  luyinplay: function (e) {
    var yuyinsrc = e.currentTarget.dataset.src;
    var myaudio = wx.createInnerAudioContext();
    myaudio.src=yuyinsrc;
    if (this.data.playing == false) {
      myaudio.play();
      this.setData({
        playing: true
      })
      myaudio.onEnded(() => {
        this.setData({
          playing: false
        })
      })
    } else {
      myaudio.pause();
      this.setData({
        playing: false
      })
    }

  },

  tijiao:function(e){
    console.log(e)
    var advice = e.detail.value.advice;
    var contact = e.detail.value.contact;
    var userid = wx.getStorageSync("userId");
    if(advice == '' || contact ==''){
        wx.showToast({
          title: '请将数据补充完整',
          icon:'none',
          duration:2000
        })
        return false;
    }
    // wx.showLoading({
    //   title: '提交中，请耐心等待。。。'
    // })
    if (wx.showLoading) {
      wx.showToast({
        icon: 'loading',
        title: '提交中，请耐心等待。。。',
        mask: true
      })
    };
    var jianyi={
      content:advice,
      contact:contact,
      user_id:userid,
    }
    
    if (this.data.yuyinsrc != ''){
        var timestamp = Date.parse(new Date()) / 1000;
        var random = Math.floor(Math.random() * 100);
        var sign = 'GHRDY65' + String(random) + String(timestamp);
        sign = md5.hexMD5(sign);
        jianyi.timestamp = timestamp;
        jianyi.random = random;
        jianyi.sign = sign;
        jianyi.voice_len = this.data.luyintime;
        var voice = this.data.yuyinsrc;
        var that = this;
        wx.uploadFile({
          url: app.static.url + 'api/user/addAdvice',
          filePath: voice,
          name: 'voice',
          formData:jianyi,
          success: function (e) {
            wx.hideLoading();
            var data = JSON.parse(e.data);
            console.log(data)
            wx.showToast({
              title: data.msg,
              icon: 'none',
              duration: 2000
            })
            setTimeout(function () {
              if (data.code == 1) {
                wx.switchTab({
                  url: '/pages/mine/user/user',
                })
              }
            }, 1000)
          }
        })
    }else if(this.data.yuyinsrc == ''){
      var jypost = {
        url: "api/user/addAdvice",
        data: jianyi,
        success: function (e) {
          wx.hideLoading();
          wx.showToast({
            title: e.data.msg,
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            if (e.data.code == 1) {
              wx.switchTab({
                url: '/pages/mine/user/user',
              })
            }
          }, 1000)
        },
        error: function (e) {
          wx.hideLoading()
          wx.showToast({
            title: e.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      };
      app.post(jypost);
    }
    
  }

})